package org.yi.web.account;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yi.core.annotation.Action;
import org.yi.core.common.Constants;
import org.yi.core.enums.RoleEnum;
import org.yi.core.helper.DuoshuoHelper;
import org.yi.core.mail.MailSenderFactory;
import org.yi.core.utils.DesUtils;
import org.yi.spider.utils.FileUtils;
import org.yi.web.account.entity.AccountEntity;
import org.yi.web.base.BaseController;
import org.yi.web.favorite.FavoriteEntity;
import org.yi.web.post.entity.PostEntity;

import weibo4j.model.User;
import weibo4j.model.WeiboException;
import weibo4j.org.json.JSONException;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.oauth.Oauth;

@Action(action = "/user")
public class UserController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	/**
	 * 进入账户管理首页
	 */
	public void index() {
		redirect("/");
	}

	public void login() {
//		if(getFrontUser() != null) {
//			redirect("/");
//		} else {
			setAttr("site", getSite());
			render("/themes/"+getSite().get("theme")+"/login.html");
//		}
	}
	
	public void doLogin() {
		String email = getPara("email");
		String password = getPara("password");
		String redirect = getPara("redirect");
        try {
        	AccountEntity account = AccountEntity.dao.getByEmail(email);
            if(account == null){
            	addError("用户名不存在!");
            	forwardAction("/user/login");
            } else if(!DigestUtils.md5Hex(password +"{" + account.getStr("login_name") + "}").equals(account.get("passwd"))) {
            	addError("密码错误!");
            	forwardAction("/user/login");
            } else {
            	account.set("login_time", Calendar.getInstance().getTime());
            	account.update();
            	getSession().setAttribute(Constants.FRONT_LOGIN_USER, account);
            	redirect = StringUtils.isBlank(redirect) ? "/" : redirect;
            	redirect(redirect);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            addError("message", "unknow error:" + e.getMessage());
        	forwardAction("/user/login");
		}
	}
	
	public void gosso() {
		String type = getPara("connect");
		getSession().setAttribute("login_current_url", getRequest().getHeader("Referer"));
		if("qq".equals(type)) {
			try {
				redirect(new Oauth().getAuthorizeURL(getRequest()));
			} catch (QQConnectException e) {
				logger.error("qq connect error: " + e.getMessage(), e);
				renderError(500);
			}
		} else if("weibo".equals(type)) {
			try {
				weibo4j.Oauth oauth = new weibo4j.Oauth();
				String url = oauth.authorize("code", "");
				redirect(url);
			} catch (Exception e) {
				logger.error("weibo connect error: " + e.getMessage(), e);
				renderError(500);
			} 
		} else {
			renderError(404);
		}
	}
	
	public void qqlogin() {
		String redirect = (String) getSession().getAttribute("login_current_url");
		redirect = StringUtils.isBlank(redirect)?"/":redirect;
		getSession().removeAttribute("login_current_url");
		 try {
			AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(getRequest());
			 String accessToken = null;
			 String openID = null;
			 if (StringUtils.isEmpty(accessTokenObj.getAccessToken())) {
			     logger.error("没有获取到响应参数");
			     renderError(500);
			 } else {
			     accessToken = accessTokenObj.getAccessToken();
			     OpenID openIDObj = new OpenID(accessToken);
			     openID = openIDObj.getUserOpenID();
			     com.qq.connect.api.qzone.UserInfo qzoneUserInfo = new com.qq.connect.api.qzone.UserInfo(accessToken, openID);
			     com.qq.connect.javabeans.qzone.UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
			     if (userInfoBean.getRet() == 0) {
			    	 AccountEntity frontUser = getFrontUser();
			    	 //  如果用户已登录， 则绑定当前用户
			    	 if (frontUser != null && StringUtils.isNotBlank(frontUser.getStr("login_name"))) {
	                    // 登录状态绑定
			    		if(StringUtils.isBlank(frontUser.getStr("sso_id"))) {
			    			frontUser.set("sso_id", openID);
			    			frontUser.set("sso_type", "qq");
			    			frontUser.set("login_time", Calendar.getInstance().getTime());
				    		frontUser.update();
			    		}
			    		DuoshuoHelper.token(frontUser, getRequest(), getResponse());
                    } else {
                    	// 根据sso_id和sso_type查找用户， 如果找到， 则使其登录， 否则跳转到绑定页面
                    	AccountEntity ssoAccount = AccountEntity.dao.findBySSO(openID, "qq");
                    	if(ssoAccount != null) {
                    		ssoAccount.set("login_time", Calendar.getInstance().getTime());
                    		ssoAccount.update();
                    		getSession().setAttribute(Constants.FRONT_LOGIN_USER, ssoAccount);
                    		DuoshuoHelper.token(ssoAccount, getRequest(), getResponse());
                    	} else {
                    		/*setAttr("redirect", getPara("redirect"));
                			setAttr("sso_id", openID);
                			setAttr("sso_type", "qq");
                			setAttr("name", userInfoBean.getNickname());
                			render("/themes/"+getSite().get("theme")+"/bind.html");*/
                    		AccountEntity account = new AccountEntity();
            				account.set("login_name", userInfoBean.getNickname());
            				account.set("email", org.yi.core.utils.StringUtils.randomStr(12) + "@yispider.com");
            				account.set("role", RoleEnum.REGISTER_USER.getCode());
            				account.set("passwd", 
            						DigestUtils.md5Hex(org.yi.core.utils.StringUtils.randomStr(32) +"{" + userInfoBean.getNickname() + "}"));
            				account.set("sso_id", openID);
            				account.set("sso_type", "qq");
            				account.set("create_time", Calendar.getInstance().getTime());
            				account.save();
            				getSession().setAttribute(Constants.FRONT_LOGIN_USER, account);
            				DuoshuoHelper.token(account, getRequest(), getResponse());
                    	}
                    }
			    	 redirect((redirect.indexOf("login") >= 0) ? "/" : redirect);
			     } else {
			    	renderError(500);
			     }
			 }
		} catch (Exception e) {
			logger.error("连接失败：" + e.getMessage(), e);
			renderError(500);
		}
	}
	
	public void weibologin(){
		String redirect = (String) getSession().getAttribute("login_current_url");
		redirect = StringUtils.isBlank(redirect)?"/":redirect;
		getSession().removeAttribute("login_current_url");
        try {
        	weibo4j.Oauth oauth = new weibo4j.Oauth();
			weibo4j.http.AccessToken accessToken = oauth.getAccessTokenByCode(getPara("code"));
			weibo4j.Account account = new weibo4j.Account(accessToken.getAccessToken());
			weibo4j.org.json.JSONObject uid = account.getUid();
			weibo4j.Users users = new weibo4j.Users(accessToken.getAccessToken());
			User loginUser = users.showUserById(uid.getString("uid"));
			if(loginUser != null) {
				AccountEntity frontUser = getFrontUser();
		    	//  如果用户已登录， 则绑定当前用户
		    	if (frontUser != null && StringUtils.isNotBlank(frontUser.getStr("login_name"))) {
		    		// 登录状态绑定
		    		if(StringUtils.isBlank(frontUser.getStr("sso_id"))) {
		    			frontUser.set("sso_id", uid.getString("uid"));
		    			frontUser.set("sso_type", "weibo");
		    			frontUser.set("login_time", Calendar.getInstance().getTime());
			    		frontUser.update();
		    		}
		    		DuoshuoHelper.token(frontUser, getRequest(), getResponse());
               } else {
	            	// 根据sso_id和sso_type查找用户， 如果找到， 则使其登录， 否则跳转到绑定页面
	               	AccountEntity ssoAccount = AccountEntity.dao.findBySSO(uid.getString("uid"), "weibo");
	               	if(ssoAccount != null) {
	               		ssoAccount.set("login_time", Calendar.getInstance().getTime());
                		ssoAccount.update();
	               		getSession().setAttribute(Constants.FRONT_LOGIN_USER, ssoAccount);
	               		DuoshuoHelper.token(ssoAccount, getRequest(), getResponse());
	               	} else {
	               		AccountEntity localAcc = new AccountEntity();
	    				localAcc.set("login_name", loginUser.getName());
	    				localAcc.set("email", org.yi.core.utils.StringUtils.randomStr(12) + "@yispider.com");
	    				localAcc.set("role", RoleEnum.REGISTER_USER.getCode());
	    				localAcc.set("passwd", 
	    						DigestUtils.md5Hex(org.yi.core.utils.StringUtils.randomStr(32) +"{" + loginUser.getName() + "}"));
	    				localAcc.set("sso_id", uid.getString("uid"));
	    				localAcc.set("sso_type", "weibo");
	    				localAcc.set("create_time", Calendar.getInstance().getTime());
	    				localAcc.set("login_time", Calendar.getInstance().getTime());
	    				localAcc.save();
	    				getSession().setAttribute(Constants.FRONT_LOGIN_USER, localAcc);
	    				DuoshuoHelper.token(localAcc, getRequest(), getResponse());
	               	}
               	}
				redirect((redirect.indexOf("login") >= 0) ? "/" : redirect);
			} else {
				logger.error("weibo connect error");
				renderError(500);
			}
		} catch (WeiboException e) {
			logger.error("weibo connect error: " + e.getMessage(), e);
			renderError(500);
		} catch (JSONException e) {
			logger.error("weibo connect error: " + e.getMessage(), e);
			renderError(500);
		} 
	}
	
	/**
	 * sso login
	 */
	/*public void dslogin(){
		String code = getPara("code");
		String url = Constants.config.getString("duoshuo.baseurl") + "/oauth2/access_token";
		HttpClient hc = new HttpClient();
		Map<String,String> params = new HashMap<String,String>();
		params.put("client_id", Constants.config.getString("duoshuo.short_name"));
		params.put("code", code);
		//{"remind_in":7776000,"access_token":"33b237c2da1acc1ff57827e680ab07b8","expires_in":7776000,"user_id":"6225897626491945729","code":0}
		String response = hc.post(url, params);
		JSONObject resJson = JSONObject.parseObject(response);
		url = Constants.config.getString("duoshuo.baseurl") + "/users/profile.json?user_id="+resJson.getString("user_id");
		//{"response":{"user_id":"4580111","name":"xiaoy","url":"http:\/\/www.yispider.com\/","avatar_url":"http:\/\/app.qlogo.cn\/mbloghead\/52bad55eff6ce67b2758\/50","threads":0,"comments":5,"social_uid":{"qq":"34F3812237E7B79C10A0DD197C70650F"},"post_votes":0,"connected_services":{"qqt":{"name":"xiaoy","email":null,"avatar_url":"http:\/\/app.qlogo.cn\/mbloghead\/52bad55eff6ce67b2758\/50","url":"http:\/\/t.qq.com\/dugudujiaozhu","description":"","service_name":"qqt"},"qzone":{"name":"浪迹天涯","avatar_url":"http:\/\/q.qlogo.cn\/qqapp\/100229475\/34F3812237E7B79C10A0DD197C70650F\/100","service_name":"qzone"}}},"code":0}
		//{"response":{"user_id":"4910740","name":"xiaoy很强大","url":"http:\/\/weibo.com\/qujianlin","avatar_url":"http:\/\/tp3.sinaimg.cn\/1789212370\/50\/5609561162\/1","threads":0,"comments":1,"social_uid":{"weibo":1789212370},"post_votes":0,"connected_services":{"weibo":{"name":"xiaoy很强大","avatar_url":"http:\/\/tp3.sinaimg.cn\/1789212370\/50\/5609561162\/1","url":"http:\/\/weibo.com\/qujianlin","description":"互联网新人求罩@@堂堂正正乃做人之本 >> 不卑、不亢、不褒贬人物、不妄言是非","service_name":"weibo"}}},"code":0}
		//{"response":{"user_id":"6225897626491945729","name":"小Q大叔","url":"javascript:void(0)","avatar_url":"http:\/\/wx.qlogo.cn\/mmopen\/SCug0ESSOH8IDic3icQxOHAkib5PheuYMibhtBhf5OMibCcLcqUkBETj7vAjap5EqVOF4dTbxj89LcvW0dVymyAtmug\/0","threads":0,"comments":0,"social_uid":{"weixin":"oKuxyuM5USiR2j6Rd_RAHbdLPbSc"},"post_votes":12,"connected_services":{"weixin":{"name":"小Q大叔","avatar_url":"http:\/\/wx.qlogo.cn\/mmopen\/SCug0ESSOH8IDic3icQxOHAkib5PheuYMibhtBhf5OMibCcLcqUkBETj7vAjap5EqVOF4dTbxj89LcvW0dVymyAtmug\/0","url":"javascript:void(0)","service_name":"weixin"}}},"code":0}
		response = hc.get(url);
		resJson = JSONObject.parseObject(response);
		if(resJson!=null && resJson.getJSONObject("response") != null && StringUtils.isNotBlank(resJson.getJSONObject("response").getString("name"))) {
			setAttr("name", resJson.getJSONObject("response").getString("name"));
			setAttr("redirect", getPara("redirect"));
			setAttr("sso_type", "duoshuo");
			setAttr("sso_id", resJson.getJSONObject("response").getString("user_id"));
			render("/themes/"+getSite().get("theme")+"/bind.html");
		} else {
			renderError(500);
		}
	}*/
	
	public void bind() {
		doRegist();
	}
	
	public void regist() {
		setAttr("site", getSite());
		render("/themes/"+getSite().get("theme")+"/regist.html");
	}
	
	public void doRegist(){
		String userName = getPara("username");
		String email = getPara("email");
		String password = getPara("password");
		try {
			if(AccountEntity.dao.getByName(userName) != null) {
				addError("用户 [" + userName + "] 已存在!");
            	forwardAction("/user/regist");
			} else if(AccountEntity.dao.getByEmail(email) != null) {
				addError("邮箱 [" + email + "] 已存在!");
				forwardAction("/user/regist");
			} else if(StringUtils.isBlank(password)) {
				addError("密码不能为空!");
				forwardAction("/user/regist");
			} else {
				AccountEntity account = new AccountEntity();
				account.set("login_name", userName);
				account.set("email", email);
				account.set("role", RoleEnum.REGISTER_USER.getCode());
				account.set("passwd", DigestUtils.md5Hex(password +"{" + userName + "}"));
				account.set("create_time", Calendar.getInstance().getTime());
				account.save();
				getSession().setAttribute(Constants.FRONT_LOGIN_USER, account);
				DuoshuoHelper.token(account, getRequest(), getResponse());
				redirect(StringUtils.isBlank(getPara("redirect"))?"/":getPara("redirect"));
			}
		} catch (Exception e) {
			logger.error("注册新用户 [" + userName + "] 失败，" + e.getMessage(), e);
			addError("注册新用户 [" + userName + "] 失败!");
			forwardAction("/user/regist");
		}
	}
	
	public void goFindPwd() {
		setHeader();
		setAttr("flag", 1);
		render("/themes/"+getSite().get("theme")+"/user/findpw.html");
	}
	
	public void findPwd() {
		String email = getPara("email");
		AccountEntity a = AccountEntity.dao.getByEmail(email);
		if(a == null) {
			addError("邮箱不存在");
			forwardAction("/user/goFindPwd");
		} else {
			// 发邮件
			try {
				String content = FileUtils.readFile(FileUtils.locateAbsolutePathFromClasspath("findpw.email").getAbsolutePath());
				String url = DesUtils.encode(""+email+"##"+Calendar.getInstance().getTimeInMillis(), 
						Constants.config.getString("des.key"));
				url = getAttr("url") + "/user/goFrontUpdatePwd?p=" + url;
				content = content.replace("#url#", url);
				MailSenderFactory.getSender().send(email, "易大师找回密码", content);
				
				setAttr("flag", 2);
				addMessage("发送成功， 请登录邮箱查收！如果收件箱中没有邮件， 可能在垃圾箱中！");
				setHeader();
				render("/themes/"+getSite().get("theme")+"/user/findpw.html");
			} catch (Exception e) {
				addError("发送邮件失败: " + e.getMessage());
				forwardAction("/user/goFindPwd");
			}
		}
	}
	
	public void goFrontUpdatePwd(){
		String param = getPara("p");
		try {
			param = DesUtils.decode(param, Constants.config.getString("des.key"));
			if(StringUtils.isNotBlank(param)) {
				String email = param.split("##")[0];
				String time = param.split("##")[1];
				long now = Calendar.getInstance().getTimeInMillis();
				if(now - Long.parseLong(time) > Constants.config.getInt("lostpwd.url.period", 24) * 60 * 60 *1000) {
					setAttr("flag", 2);
					addMessage("链接已失效");
				} else {
					setAttr("email", email);
					setAttr("flag", 1);
					setHeader();
				}
				render("/themes/"+getSite().get("theme")+"/user/newpwd2.html");
			} else {
				renderError(404);
			}
		} catch(Exception e) {
			logger.error(e.getMessage(), e);
			renderError(500);
		}
	}
	
	public void goUpdatePwd(){
		setHeader();
		render("/themes/"+getSite().get("theme")+"/user/newpwd.html");
	}
	
	public void updatePwd() {
		String oldpass = getPara("oldpass");
		String newpass = getPara("newpass");
		AccountEntity user = getFrontUser();
		if(!DigestUtils.md5Hex(oldpass +"{" + user.getStr("login_name") + "}").equals(user.getStr("passwd"))) {
			addError("原密码输入错误!");
			forwardAction("/user/goUpdatePwd");
		} else if(newpass==null || newpass.length()<6 || newpass.length()>32) {
			addError("新密码长度错误!");
			forwardAction("/user/goUpdatePwd");
		} else {
			user.set("passwd", DigestUtils.md5Hex(newpass +"{" + user.getStr("login_name") + "}"));
			user.update();
			addError("密码修改成功!");
		}
		forwardAction("/user/goUpdatePwd");
	}
	
	public void updateLostPwd() {
		String newpass = getPara("newpass");
		String email = getPara("email");
		if(newpass==null || newpass.length()<6 || newpass.length()>32) {
			setAttr("flag" ,1);
			setAttr("email", email);
			addError("新密码长度错误!");
		} else {
			AccountEntity user = AccountEntity.dao.getByEmail(email);
			if(user == null) {
				setAttr("flag" ,2);
				addMessage("参数错误!");
			} else {
				user.set("passwd", DigestUtils.md5Hex(newpass +"{" + user.getStr("login_name") + "}"));
				user.update();
				setAttr("flag" ,2);
				addMessage("密码修改成功!");
			}
		}
		setHeader();
		render("/themes/"+getSite().get("theme")+"/user/newpwd2.html");
	}
	
	public void goFavorite() {
		AccountEntity user = getFrontUser();
		if(user.get("id") == null || StringUtils.isBlank(String.valueOf(user.get("id")))) {
			login();
		} else {
			List<FavoriteEntity> favoriteList = FavoriteEntity.dao.getByUid(user.get("id"));
			List<Object> idList = new ArrayList<Object>();
			for(FavoriteEntity f : favoriteList) {
				idList.add(f.get("article_id"));
			}
			setHeader();
			setAttr("list", PostEntity.dao.getByIdList(idList.toArray()));
			render("/themes/"+getSite().get("theme")+"/user/myfav.html");
		}
	}
	
	public void logout() {
		getSession().invalidate();
		String redirectUrl = getPara("redirect");
		redirectUrl = StringUtils.isBlank(redirectUrl) ? "/" : redirectUrl;
		redirect(redirectUrl);
	}
}
